package org.grow.auth.controller;

import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.auth.dao.RouteConfigRepository;
import org.grow.auth.entity.QRoleInfo;
import org.grow.auth.entity.QRoleRoute;
import org.grow.auth.entity.QRouteConfig;
import org.grow.auth.entity.RouteConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: xwg
 * @CreateDate: 2021/11/2
 */

@RestController
@RequestMapping("/auth/route")
public class RouteController {
    @Autowired
    private RouteConfigRepository routeConfigRepository;

    @GetMapping("/supplyAll")
    public List<RouteConfig> supplyAllRoutes() {

        return routeConfigRepository.findAll();
    }


    QRoleInfo r = QRoleInfo.roleInfo;
    QRoleRoute rr = QRoleRoute.roleRoute;
    QRouteConfig rc = QRouteConfig.routeConfig;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @GetMapping("/supplyByUser")
    public List<RouteConfig> supplyByUser() {
        Collection<? extends GrantedAuthority> authorities =
                SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        List<String> roles = authorities.stream().map(x -> x.getAuthority()).collect(Collectors.toList());
        /**
         * select distinct rc.*
         * from RoleInfo r
         * inner join RoleRoute rr on r.roleId = rr.roleFk
         * inner join RouteConfig rc on rr.routeFk = rc.routeId
         * where r.roleName in ('leaveAuditor','orgDesigner')
         */
        List<RouteConfig> fetch = jpaQueryFactory.selectDistinct(rc)
                .from(r)
                .innerJoin(rr).on(r.roleId.eq(rr.roleFk))
                .innerJoin(rc).on(rr.routeFk.eq(rc.routeId))
                .where(r.roleName.in(roles))
                .fetch();
        String name = SecurityContextHolder.getContext().getAuthentication().getName();

        System.out.println("登录人：" + name + " 拥有的页面权限是： " + fetch);
        return fetch;


    }
}
